package com.tianquan.client.loadBalan.strategy;

import com.tianquan.client.registry.ClientInstanceManager;
import com.tianquan.common.instance.ServiceInstance;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * @Author: tianquan
 * @date: 2024-11-04  15:15
 * @Description: 加权轮询负载均衡
 */
public class WeightedRoundRobinLoadBalancer implements LoadBalancer {

    private List<ServiceInstance> serviceInstances;
    private int[] currentWeights;
    private int maxWeight;

    @Override
    public ServiceInstance choose(String serviceName) {
        // 获取指定的服务列表
        Set<ServiceInstance> instanceSet = ClientInstanceManager.getInstance(serviceName);
        if (instanceSet == null || instanceSet.isEmpty()) {
            return null;
        }
        // 更新服务列表
        serviceInstances = new ArrayList<>(instanceSet);
        // 初始化权重数组
        this.currentWeights = new int[serviceInstances.size()];
        // 找到最大权重
        this.maxWeight = 0;
        for (int i = 0; i < serviceInstances.size(); i++) {
            ServiceInstance instance = serviceInstances.get(i);
            int weight = instance.getWeight();
            if (weight > maxWeight) {
                maxWeight = weight;
            }
        }

        return selectInstance();
    }

    public ServiceInstance selectInstance() {
        int selectedIndex = -1;
        for (int i = 0; i < serviceInstances.size(); i++) {
            if (selectedIndex == -1 || currentWeights[i] > currentWeights[selectedIndex]) {
                selectedIndex = i;
            }
        }
        for (int i = 0; i < serviceInstances.size(); i++) {
            if (i == selectedIndex) {
                currentWeights[i] -= maxWeight;
            } else {
                currentWeights[i] += serviceInstances.get(i).getWeight();
            }
        }
        return serviceInstances.get(selectedIndex);
    }

}
